package com.yc.thread;

import java.util.Random;

/**
 * 小项目：需求：现在有10张票，一个窗口是个柜员
 * 要求：1.随机出票，不能买不存在的票。2.柜员不能卖相同的id票 1号票不能被2个柜员卖
 * */
public class Test16_synchronized {
    public static void main(String[] args) {
        SellTickOp sto = new SellTickOp(  20);
        for( int i=1;i<=100;i++) {
            Thread counter1 = new Thread(sto,"柜员====="+i);
            counter1.start();
        }

    }


}

class SellTickOp implements Runnable{
    int tickets;//总票数
    Random r= new Random();
    public SellTickOp(int tickets){
        this.tickets=tickets;
    }
    @Override
    public void run() {
        while (true ) {
            synchronized (this){
                if (tickets > 0) {
                    System.out.println(Thread.currentThread().getName() + "在sell第" + (tickets--) + "张票");
                    try {
                        Thread.sleep(100);
                        //wait(r.next(100)) //必须与synchronized结合使用
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } else {
                    return;
                }
            }
        }
    }
}
